package cn.kgc.thread.demo2;

import java.util.concurrent.*;

/**
 * <p>添加描述信息</p>
 *
 * @author 卢传琪
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService=
                Executors.newScheduledThreadPool(10);
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程池中执行的任务");
            }
        },5,TimeUnit.SECONDS);
        scheduledExecutorService.shutdown();
    }

    private static void method4() {
        //new ThreadPoolExecutor(0, Integer.MAX_VALUE,
        //           60L, TimeUnit.SECONDS,
        //          new SynchronousQueue<Runnable>())
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(()->{
            System.out.println("线程池中的线程执行任务");
        });

        executorService.shutdown();
    }

    private static void method3() {
        //创建指定数量的线程池
        //new ThreadPoolExecutor(nThreads, nThreads,
        //         0L, TimeUnit.MILLISECONDS,
        //        new LinkedBlockingQueue<Runnable>())
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(()->{
            System.out.println("线程池中的线程执行任务");
        });

        executorService.shutdown();
    }

    private static void method2() {
        //创建一个单实例的线程
        //new ThreadPoolExecutor(1, 1,
        //            0L, TimeUnit.MILLISECONDS,
        //            new LinkedBlockingQueue<Runnable>())
        //ExecutorService:线程池的顶级接口
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        executorService.execute(()->{
            System.out.println("线程池中的线程执行任务");
        });

        executorService.shutdown();
    }

    private static void method1() {
        //corePoolSize:核心线程数
        //maximumPoolSize:最大线程数
        //keepAliveTime:线程空闲时间
        //unit:时间单位
        //workQueue:阻塞队列
        //        ArrayBlockingQueue：有界队列
        //      LinkedBlockingQueue：无界队列
        //threadFactory:线程工厂
        //handler:拒绝策略
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(5, 10, 5,
                        TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
                        Executors.defaultThreadFactory()
                ,new ThreadPoolExecutor.AbortPolicy());

        //让线程池执行任务
        threadPoolExecutor.execute(()->{
            System.out.println("线程池执行任务"+Thread.currentThread().getName());
        });

        //关闭线程池：shutdown 关闭线程，线程池中的任务继续执行，但是此时就不能像线程池中添加任务
        threadPoolExecutor.shutdown();
    }
}
